#include"fraction.h"
void fraction::gcd() {
    if(q<0){
        q=-q;
        p=-p;
    }
int temp1 = abs(p), temp2 = q;
	if (temp1 < temp2)
		swap(temp1, temp2);
	while (temp2) {
		temp1 %= temp2;
		swap(temp1, temp2);
	}
    p /= temp1;
	q /= temp1;
}
fraction fraction::operator + (fraction& b) {
	fraction a;
	a.p = p * b.q + b.p * q;
	a.q = q * b.q;
	a.gcd();
	return a;
}
fraction fraction::operator - (fraction& b) {
	fraction c;
	c.p = 0 - b.p;
	c.q = b.q;
	fraction d = *this + c;
	return d;
};
fraction fraction::operator * (fraction& b) {
	fraction a;
	a.p = p * b.p;
	a.q = q * b.q;
	a.gcd();
	return a;
};
fraction fraction::operator / (fraction& b) {
	if (b.p == 0) {
		fraction c(ERROR_CODE);
		return c;
	}
	fraction c;
    c.p = b.q;
    c.q = b.p;
    fraction d = *this * c;
	return d;
};
bool fraction::operator == (fraction& b) {
	if (p * b.q == q * b.p)
		return 1;
	else
		return 0;
};
QString fraction::print() {
    QString t="";
    if(p==ERROR_CODE)
    {
        t="该值不存在！";
        return t;
    }
    if (q != 1 && p!=0)
        t.append(QString::number(p)+"/"+QString::number(q));
	else
        t.append(QString::number(p));
    return t;
}
fraction operator +(int a, fraction& b) {
	fraction c(a);
	fraction d = c + b;
	return d;
};
fraction operator +(fraction& b, int a) {
	fraction c(a);
	fraction d = c + b;
	return d;
};
fraction operator -(int a, fraction& b) {
	fraction c(a);
	fraction d = c - b;
	return d;
};
fraction operator -(fraction& b, int a) {
	fraction c(a);
	fraction d = b - c;
	return d;
};
fraction operator *(int a, fraction& b) {
	fraction c(a);
	fraction d = c * b;
	return d;
};
fraction operator *(fraction& b, int a) {
	fraction c(a);
	fraction d = c * b;
	return d;
};
fraction operator /(int a, fraction& b) {
	fraction c(a);
	fraction d = c / b;
	return d;
};
fraction operator /(fraction& b, int a) {
	fraction c(a);
	fraction d = c / b;
	return d;
};

